package com.itqf.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * projectName: rbacgp8
 *
 * @author: 赵伟风
 * time: 2021/8/13 10:14
 * description:使用Shiro进行认证
 */
public class AuthenticationDemo {

    public static void main(String[] args) {


        //1. 获取SecurityManager
        IniSecurityManagerFactory factory =
                new IniSecurityManagerFactory("classpath:shiro.ini");


        //securityManager有了,同时也有iniRealm
        //创建securityManager和iniRealm
        SecurityManager securityManager = factory.getInstance();

        //将securityManager存储到SecurityUtils的静态变量上!全局可用!

        SecurityUtils.setSecurityManager(securityManager);

        //2. 根据SecurityManager获取subject
        Subject subject = SecurityUtils.getSubject();

        //3. 使用subject进行认证
        UsernamePasswordToken token = new UsernamePasswordToken("root", "admin");

        try {
            /**
             * 调用认证器认证方法, 根据账号 读取 iniRealm [linkedHashMap] 争取数据! info -- 密码对比!
             * 对比通过! authenticated = true
             *
             * 验证: realm不做密码校验!
             */
            subject.login(token);
            //4. 等待认证结果
            System.out.println("认证成功");
        }catch (AuthenticationException e){
            System.out.println("认证失败!"+ e.getMessage());
        }

        //账号和密码
        //手机号和验证码
        //第三账号和授权码

        //Principal = 账号
        //credential = 密码

        //认证通过以后,默认情况获取认证的账号!
        Object principal = subject.getPrincipal();

        System.out.println("principal = " + principal);


        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);
        //5.取消认证
        if (authenticated) {
            subject.logout();
        }





    }

}
